from django.shortcuts import render
from myback.models import *
from django.http import HttpResponse, JsonResponse
import json
from django.core import serializers


# Create your views here.
def stg_display(request):
    customerid = request.GET.get("customerid") if request.GET.get("customerid") else ""
    request.session['customerid'] = customerid
    return render(request, '../../myback/templates/strategy.html', locals())


def stg_detail(request):
    stgid = request.GET.get("stgid") if request.GET.get("stgid") else ""
    stgfile = ""
    if TBackapproval.objects.using("BackTestDB").filter(stgid=stgid).exists():
        stgfile = TBackapproval.objects.using("BackTestDB").values("stgfile").filter(stgid=stgid).first().get("stgfile")
    return render(request, '../../myback/templates/stgdetail.html', locals())


# 历史回测页面
def back_html(request):
    stgid = request.GET.get("stgid") if request.GET.get("stgid") else ""
    return render(request, '../../myback/templates/backdetail.html', locals())


def back_detail(request):
    """
    :param request:本接口执行查看策略的回测详情 即t_backrun表
    :return: queryset--->query-list
    """
    stgid = request.POST.get("stgid") if request.POST.get("stgid") else ""
    back_obj_list = ""
    try:
        if TBackrun.objects.using("BackTestDB").filter(stgid=int(stgid)).exists():
            back_obj_list = serializers.serialize("json", TBackrun.objects.using("BackTestDB").filter(stgid=int(stgid)))
        return JsonResponse({"back_obj_list": back_obj_list, "type": 1}, safe=False)
    except Exception as e:
        return JsonResponse({"back_obj_list": str(e), "type": 0}, safe=False)
